package cn.haoxsf.app.system.controller;


import cn.haoxsf.app.common.api.CommonResult;
import cn.haoxsf.app.common.api.enums.ImagesExceptionEnum;
import cn.haoxsf.app.common.exception.BaseException;
import cn.haoxsf.app.common.util.ToolUtil;

import cn.haoxsf.app.system.entity.FileInfo;
import cn.haoxsf.app.system.service.IFileInfoService;
import com.qiniu.common.QiniuException;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * <p>
 * 文件信息表 前端控制器
 * </p>
 *
 * @author Ele  qvbanfm@qq.com
 * @since 2020-01-09
 */
@RestController
@RequestMapping("/upload")
@Log4j2
@Api(tags = "文件上传", value = "上传和删除相关请求")
public class FileInfoController {
    @Autowired
    private IFileInfoService fileInfoService;

    @RequestMapping(value = "/image", method = RequestMethod.POST)
    @ApiOperation(value = "图片上传", notes = "图片上传")
    public CommonResult uploadImages(@ApiParam("图片文件") @RequestParam(value = "file", required = false) MultipartFile[] file) {
        if (ToolUtil.isEmpty(file)) {
            throw new BaseException(ImagesExceptionEnum.THE_PICTURE_IS_EMPTY);
        }
        Collection<FileInfo> fileInfos = new ArrayList<>();
        try {
            fileInfos = fileInfoService.uploadImages(file);
        } catch (BaseException e) {
            return CommonResult.error(e.getCode(), e.getMsg());
        } catch (IOException e) {
            log.error("上传图片出错={}", e.getMessage());
        }
        return CommonResult.success(fileInfos);
    }

    @ApiOperation(value = "删除图片", notes = "删除图片")
    @RequestMapping(value = "image/delete", method = RequestMethod.POST)
    public CommonResult delete(@ApiParam(value = "图片唯一id", required = true) @RequestParam String finalName) {
        if (ToolUtil.isNotEmpty(finalName)) {
            try {
                fileInfoService.deleteImages(finalName);
            } catch (QiniuException e) {
                log.error("删除七牛云的图片出错:[{}]");
                return CommonResult.error(ImagesExceptionEnum.IMAGES_NAME_IS_EMPTY);
            }
            return CommonResult.success();
        } else {
            return CommonResult.error(ImagesExceptionEnum.IMAGES_NAME_IS_EMPTY);
        }
    }
}
